package com.websocket.web.server;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.ParameterMap;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: xwj
 * @date: 2019/5/24
 */
@ServerEndpoint
@Component
public class WebSocketServer {
    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    /**
     * 在线人数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * 全部在线会话  PS: 基于场景考虑 这里使用线程安全的Map存储会话对象。
     */
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, ParameterMap parameterMap) throws IOException {
        onlineSessions.put(session.id().toString(), session);
        int count = onlineCount.incrementAndGet();
        logger.info("有连接{}加入，当前连接数为：{}", session.id().toString(), count);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        int count = onlineCount.decrementAndGet();
        logger.info("有连接{}关闭，当前连接数为：{}", session.id().toString(), count);
        onlineSessions.remove(session.id().toString());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        logger.error("通信异常:{}", throwable.getMessage());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        broadcastMessage(message);
    }

    /**
     * 群发消息
     *
     * @param msg
     */
    private static void broadcastMessage(String msg) {
        onlineSessions.forEach((id, session) -> {
            session.sendText(msg);
        });
    }
}
